<?php


namespace App\Utils;
use AlibabaCloud\Client\AlibabaCloud;
use Illuminate\Support\Facades\Log;

class AliSms
{
    /**
     * @param string $mobile
     * @param string $templateCode
     * @param array $templateParams
     * @return Output
     */
    static function sendMsg($mobile, $templateCode, $templateParams = [])
    {
        try {
            AlibabaCloud::accessKeyClient(config('sms.ali.access_key_id'), config('sms.ali.access_secret'))
                ->regionId('cn-hangzhou')// replace regionId as you need
                ->asDefaultClient();
            $query = [
                'RegionId' => "default",
                'PhoneNumbers' => $mobile,
                'SignName' => config('sms.ali.sign_name'),
                'TemplateCode' => $templateCode
            ];
            if (count($templateParams)) {
                $query['TemplateParam'] = json_encode($templateParams);
            }
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => $query
                ])
                ->request()->toArray();
            if ($result['Code'] == 'OK') {
                return Output::success('发送成功');
            } else {
                Log::info("短信发送失败:" . $result['Message'] . '\r\n参数:' . json_encode($templateParams));
                return Output::fail($result['Message']);
            }
        } catch (\Exception $e) {
            return Output::error($e,'短信发送失败');
        }
    }
}